import storage from 'store'
import {
	login,
	getinfo,
	logout
} from '@/api/user';
import {
	TUILogin
} from '@tencentcloud/tui-core';
const user = {
	state: {
		token: '',
		info: {}
	},
	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},

		SET_INFO: (state, info) => {
			state.info = info
		}
	},

	actions: {
		// 登录
		Login({
			commit,
			state
		}, userInfo) {
			return new Promise((resolve, reject) => {
				// 将code发送到后端
				console.log('token', userInfo);
				login(userInfo).then(res => {
						console.log("获取用户信息", res);

						if (res.code === 200) { // 判断返回是否为成功状态
							console.log('yonghuxi', res);
							commit('SET_TOKEN', res.result.token);
							uni.setStorageSync('token', res.result.token);
							resolve(res);
						} else {
							console.error('接口返回失败:', res.message);
							reject(res.message); // 如果失败，返回错误信息
						}
					})
					.catch((error) => {
						// console.log('错误捕获', error)

						reject(error)
					})
			})
		},
		GetuserInfo({
			commit,
			state
		}) {
			return new Promise((resolve, reject) => {
				getinfo().then(res => {
					// console.log('用户信息', res);

					uni.setStorageSync("userinfo", JSON.stringify(res.result))
					commit('SET_INFO', res.result)
					resolve(res)
				}).catch((error) => {
					// console.log('错误捕获', error)

					reject(error)
				})
			})
		},

		// 登出
		Logout({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				// logout(state.token)
				logout()
					.then((res) => {
						commit('SET_TOKEN', '')
						commit('SET_INFO', {})
						uni.removeStorageSync("token")
						uni.removeStorageSync("userinfo")
						if (uni.getStorageSync("isReady")) {
							// TUILogin.logout()
						} else {
							uni.setStorageSync("isReady", false)
						}
						resolve(res)
					})
					.catch((err) => {
						console.log('logout fail:', err)
						// resolve()
					})
					.finally(() => {})
			})
		}
	}
}

export default user